package cn.itcast.service.impl;

import cn.itcast.domain.Dept;
import cn.itcast.domain.User;
import cn.itcast.factory.MapperFactory;
import cn.itcast.mapper.UserMapper;
import cn.itcast.service.UserService;
import cn.itcast.utils.TransactionUtil;
import cn.itcast.utils.UuidUtils;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.formula.functions.T;

import java.util.List;

public class UserServiceImpl implements UserService {
    //查询所有
    public List<User> findAll(int pageNum) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //分页
        PageHelper.startPage(pageNum,5);
        List<User> userList = mapper.findAll();
        TransactionUtil.close(sqlSession);
        return userList;
    }

    //添加用户
    public void add(User user) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        user.setId(UuidUtils.getUuid());
        mapper.add(user);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);

    }

    @Override
    public User findById(String id) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user =   mapper.findById(id);


        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
        return user;
    }

    @Override
    public void update(User user) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.update(user);
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void deleteByIds(String ids) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        if (ids != null && ids.length()>0){
            String[] sts = ids.split(",");
            mapper.deleteByIds(sts);
        }

        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }
}
